import time
import xlwings as xw

def write_excel(page_name, results):
    app = xw.App(visible=False)
    wb = app.books.open('d:/log/didiao.xlsx')
    ws = wb.sheets[page_name]
    date = time.strftime('%m-%d %H:%M:%S', time.localtime())
    for result in results:
        name, url = result
        rng = ws.range(1,1).expand()
        fir_col = rng.columns(1).value
        if fir_col == None:
            row_num = results.index(result) + 1
            ws.range((row_num,1), (row_num,3)).value = [name, url, date]
        else:
            if name in fir_col:
                row_num = fir_col.index(name) + 1
                column_num = ws.range(row_num,1).expand('right').last_cell.column + 1
                ws.range(row_num, column_num).value = date
            else:
                print('新增', name, url)
                row_num = rng.rows.count + 1
                ws.range((row_num, 1), (row_num, 3)).value = [name, url, date]
    rng = ws.range(1,1).expand().value
    ws.autofit()
    wb.save('d:/log/didiao.xlsx')
    wb.close()
    app.quit()

with open('d:/log/results.txt', 'r', encoding='utf-8') as f:
    results = f.readlines()
results = [eval(i.strip()) for i in results]
page_name = input('哪个主题？\n')
write_excel(page_name, results)